package org.chintoooor.trio.server.http;

import java.util.Formatter;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;

public class HttpParser {

	public HttpRequest parseRequest(String httpRequestString) {
		HttpRequest httpRequest = new HttpRequest();
		try {
			String[] httpRequestLines = httpRequestString.split("\r\n");
			String[] firstLineTokens = httpRequestLines[0].split("\\s");
			HttpOperation httpOperation = HttpOperation
					.valueOf(firstLineTokens[0]);
			String serverLocation = firstLineTokens[1];
			String protocolVersion = firstLineTokens[2];
			httpRequest.setHttpOperation(httpOperation);
			httpRequest.setLocation(serverLocation);
			httpRequest.setHttpVersion(protocolVersion);
			for (int i = 1; i < httpRequestLines.length; i++) {
				String headerTokens[] = httpRequestLines[i].split(":\\s");
				if (headerTokens.length > 2)
					throw new RuntimeException("Cannot parse header line "
							+ httpRequestLines[i]);
				httpRequest.setProperty(headerTokens[0], headerTokens[1]);
			}
		} catch (RuntimeException runtimeException) {
			httpRequest.setParseException(runtimeException);
		}
		return httpRequest;
	}

	public String encodeResponse(HttpResponse httpResponse) {
		StringBuilder httpResponseBuilder = new StringBuilder(1024);
		Formatter formatter = new Formatter(httpResponseBuilder, Locale.ROOT);
		formatter.format("%s %d %s\r\r", httpResponse.getProtocolVersion(),
				httpResponse.getResponseCode(),
				httpResponse.getResponseMessage());
		Set<Entry<Object, Object>> headerPropertiesSet = httpResponse
				.getHeaderProperties().entrySet();
		Iterator<Entry<Object, Object>> headersIterator = headerPropertiesSet
				.iterator();
		while (headersIterator.hasNext()) {
			Entry<Object, Object> headerEntry = headersIterator.next();
			formatter.format("%s: %s\r\n", headerEntry.getKey(),
					headerEntry.getValue());
		}
		formatter.format("%s", httpResponse.getMessageBody());
		return httpResponseBuilder.toString();
	}
}
